package com.kaikeba.wx.controller;

import com.kaikeba.bean.*;
import com.kaikeba.mvc.ResponseBody;
import com.kaikeba.service.CourierService;
import com.kaikeba.service.ExpressService;
import com.kaikeba.service.UserService;
import com.kaikeba.util.DateFormatUtil;
import com.kaikeba.util.JsonUtil;
import com.kaikeba.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Stream;

/**
 * @Author: 平川
 * @Description:
 * @Date Created in 2021-08-03 19:57
 * @Modified By:
 */
public class ExpressController {
    @ResponseBody("/wx/findExpressByUserPhone.do")
    public String findByUserPhone(HttpServletRequest req, HttpServletResponse resp){
        /*
        * 思路: 判断用户是不是快递员
        * */
        Courier courier = UserUtil.getWxCourier(req.getSession());
        String userphone = null;
        if (courier==null){
           //是普通用户
            User user = UserUtil.getWxUser(req.getSession());
            userphone = user.getPhonenumber();
        }else{
            userphone = courier.getPhonenumber();
        }
        List<Express> list = ExpressService.findByUserPhone(userphone);

        ArrayList<BootStrapTableExpress> list2 = new ArrayList<>();
        for (Express e : list){
            String intime = DateFormatUtil.format(e.getIntime());
            String outtime = e.getOuttime()==null?"未出库":DateFormatUtil.format(e.getOuttime());
            String status = e.getStatus()==0?"待取件":"已取件";
            String code = e.getCode()==null?"已取件":e.getCode();
            BootStrapTableExpress e2 = new BootStrapTableExpress(e.getId(),e.getNumber(),e.getUsername(),e.getUserphone(),e.getCompany(),code,intime,outtime,status,e.getSysPhone());

            list2.add(e2);
        }

        Message msg = new Message();

        if (list2.size()>0){
            msg.setStatus(0); //表示这个用户是有数据的
            Stream<BootStrapTableExpress> status0Express = list2.stream().filter(express -> {
                if (express.getStatus() .equals("待取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1,o2) ->{
                long o1Time = DateFormatUtil.toTime(o1.getIntime());
                long o2Time =  DateFormatUtil.toTime(o2.getIntime());
                return (int)(o1Time-o2Time);
            });
            Stream<BootStrapTableExpress> status1Express = list2.stream().filter(express -> {
                if (express.getStatus().equals("已取件")){
                    return true;
                }else{
                    return false;
                }
            }).sorted((o1,o2) ->{
                long o1Time =  DateFormatUtil.toTime(o1.getIntime());
                long o2Time =  DateFormatUtil.toTime(o2.getIntime());
                return (int)(o1Time-o2Time);
            });
            Object[] s0 = status0Express.toArray();
            Object[] s1 = status1Express.toArray();

            Map data = new HashMap<>();
            data.put("status0",s0);
            data.put("status1",s1);
            msg.setData(data);

        }else{
            msg.setStatus(-1); //表示是没有值的
        }
        String json = JsonUtil.toJSON(msg.getData());

        return json;
    }

    @ResponseBody("/wx/userExpressList.do")
    public String expressList(HttpServletRequest req, HttpServletResponse resp){
        String userphone = req.getParameter("userphone");
        List<Express> list = ExpressService.findByUserPhoneAndStatus(userphone,0);
        ArrayList<BootStrapTableExpress> list2 = new ArrayList<>();
        for (Express e : list){
            String intime = DateFormatUtil.format(e.getIntime());
            String outtime = e.getOuttime()==null?"未出库":DateFormatUtil.format(e.getOuttime());
            String status = e.getStatus()==0?"待取件":"已取件";
            String code = e.getCode()==null?"已取件":e.getCode();
            BootStrapTableExpress e2 = new BootStrapTableExpress(e.getId(),e.getNumber(),e.getUsername(),e.getUserphone(),e.getCompany(),code,intime,outtime,status,e.getSysPhone());

            list2.add(e2);
        }
        Message msg = new Message();
        if (list.size()==0){
            msg.setStatus(-1);
            msg.setResult("未查询到快递");
        }else{
            msg.setStatus(0);
            msg.setResult("查询成功！");
            msg.setData(list2);
        }
        return JsonUtil.toJSON(msg);
    }
    @ResponseBody("/wx/insert2.do")
    public String insert2(HttpServletRequest req, HttpServletResponse resp){

        String number = req.getParameter("number");
        String company = req.getParameter("company");
        String username = req.getParameter("username");
        String userphone1 = req.getParameter("userphone1");
        Express express = new Express(number,username,userphone1,company, UserUtil.getUserPhone(req.getSession()));
        boolean flag = ExpressService.insert(express);
        Message message = new Message();
        if (flag){
            //录入成功！
            message.setStatus(0);
            message.setResult("快递录入成功！");
        }else {
            //录入失败！
            message.setStatus(-1);
            message.setResult("快递录入失败！");
        }
        String json = JsonUtil.toJSON(message);
        return json;
    }
    @ResponseBody("/wx/indexQueryExpress.do")
    public String indexQueryExpress(HttpServletRequest req, HttpServletResponse resp){
        String number = req.getParameter("number");
        Express e = ExpressService.findByNumber(number);
        Message msg = new Message();
        if (e!=null){
            //查询到此快递
            msg.setStatus(0);
            msg.setResult("找到此快递");
            String intime = DateFormatUtil.format(e.getIntime());
            String outtime = e.getOuttime()==null?"未出库":DateFormatUtil.format(e.getOuttime());
            String code = e.getCode()==null?"已取件":e.getCode();
            String status = e.getStatus()==0?"未取件":"已取件";
            BootStrapTableExpress e2 =
                    new BootStrapTableExpress(e.getId(),e.getNumber(),e.getUsername(),e.getUserphone(),e.getCompany(),code,intime,outtime,status,e.getSysPhone());
            msg.setData(e2);
        }else{
            msg.setStatus(-1);
            msg.setResult("未找到此快递");
        }
        return JsonUtil.toJSON(msg);
    }
    @ResponseBody("/wx/updateUsernameUserphone.do")
    public String updateUsernameUserphone(HttpServletRequest req, HttpServletResponse resp) {
        String code = req.getParameter("code");
        String username = req.getParameter("username");
        String userphone = req.getParameter("userphone");
        String sysCode = UserUtil.getLoginSms(req.getSession(), userphone);
        Message msg = new Message();
        if (Objects.equals(code, sysCode)) {
            //验证码相等
            msg.setStatus(0);
            msg.setResult("修改成功！");
            /*----------------------------------------*/
            Courier courier = UserUtil.getWxCourier(req.getSession());
            if (courier != null) {
                int courierid = courier.getId();
                //1.根据id到快递员表格里面去修改 2.去快递里面查找此手机号，去修改手机号与姓名
                CourierService.updateUsernameUserphone(courierid, username, userphone);
                //根据手机号去快递列表里面查询
                String p = courier.getPhonenumber();
                List<Express> list = ExpressService.findByUserPhone(p);
                if (list.size() != 0) {
                    //循环遍历
                    for (Express e : list) {
                        //获取e的id
                        int eid = e.getId();
                        //根据id去修改用户名与手机号
                        ExpressService.updateUsernameUserphone(eid, username, userphone);
                    }
                }
            } else {
                User user = UserUtil.getWxUser(req.getSession());
                int id = user.getId();
                //去用户表，根据id去修改
                UserService.updateUsernameUserphone(id,username,userphone);
                //根据手机号去快递表里修改
                String phonenumber = user.getPhonenumber();
                List<Express> list = ExpressService.findByUserPhone(phonenumber);
                if (list.size() != 0) {
                    //循环遍历
                    for (Express e : list) {
                        //获取e的id
                        int eid = e.getId();
                        //根据id去修改用户名与手机号
                        ExpressService.updateUsernameUserphone(eid, username, userphone);
                    }
                }
            }

        } else {
            //验证码不相等
            msg.setStatus(-1);
            msg.setResult("验证码不相等！");

            /*
             * 1.思路：现在快递员里面查找，再到用户里面查找
             * */
        }
        return JsonUtil.toJSON(msg);
    }
    @ResponseBody("/wx/updateUsernameUserphonePassword.do")
    public String updateUsernameUserphonePassword(HttpServletRequest req, HttpServletResponse resp){
        final String password = req.getParameter("password");
        String code = req.getParameter("code");
        String username = req.getParameter("username");
        String userphone = req.getParameter("userphone");
        String sysCode = UserUtil.getLoginSms(req.getSession(), userphone);
        Message msg = new Message();
        if (Objects.equals(code, sysCode)) {
            //验证码相等
            msg.setStatus(0);
            msg.setResult("修改成功！");
            /*----------------------------------------*/
            Courier courier = UserUtil.getWxCourier(req.getSession());
            if (courier != null) {
                int courierid = courier.getId();
                //1.根据id到快递员表格里面去修改 2.去快递里面查找此手机号，去修改手机号与姓名
                CourierService.updateUsernameUserphonePassword(courierid, username, userphone,password);
                //根据手机号去快递列表里面查询
                String p = courier.getPhonenumber();
                List<Express> list = ExpressService.findByUserPhone(p);
                if (list.size() != 0) {
                    //循环遍历
                    for (Express e : list) {
                        //获取e的id
                        int eid = e.getId();
                        //根据id去修改用户名与手机号
                        ExpressService.updateUsernameUserphone(eid, username, userphone);
                    }
                }
            } else {
                User user = UserUtil.getWxUser(req.getSession());
                int id = user.getId();
                //去用户表，根据id去修改
                UserService.updateUsernameUserphonePassword(id,username,userphone,password);
                //根据手机号去快递表里修改
                String phonenumber = user.getPhonenumber();
                List<Express> list = ExpressService.findByUserPhone(phonenumber);
                if (list.size() != 0) {
                    //循环遍历
                    for (Express e : list) {
                        //获取e的id
                        int eid = e.getId();
                        //根据id去修改用户名与手机号
                        ExpressService.updateUsernameUserphone(eid, username, userphone);
                    }
                }
            }

        } else {
            //验证码不相等
            msg.setStatus(-1);
            msg.setResult("验证码不相等！");

            /*
             * 1.思路：现在快递员里面查找，再到用户里面查找
             * */
        }
        return JsonUtil.toJSON(msg);
    }
    
}
